<!-- Tiandimapbox.vue -->
<script setup>
import { ref, onMounted } from "vue";
import mapboxgl from "mapbox-gl";
import proj4 from "proj4";
import "mapbox-gl/dist/mapbox-gl.css";

proj4.defs("EPSG:4490", "+proj=longlat +ellps=GRS80 +no_defs");

const props = defineProps({
  token: String,
  center: { type: Array, default: () => [113.72891, 34.77358] },
  zoom: { type: Number, default: 11 },
});

const mapContainer = ref(null);
const map = ref(null);

onMounted(() => {
  if (!mapboxgl.supported()) {
    console.error("WebGL not supported");
    return;
  }

  // 转换坐标系
  const [lng, lat] = proj4("EPSG:4490", "EPSG:4326", props.center);

  map.value = new mapboxgl.Map({
    container: mapContainer.value,
    style: {
      version: 8,
      sources: {
        "tdt-vec": {
          type: "raster",
          tiles: [
            `http://t0.tianditu.gov.cn/img_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=${props.token}`,
          ],
          tileSize: 256,
        },
      },
      layers: [
        {
          id: "tdt-vec-layer",
          type: "raster",
          source: "tdt-vec",
        },
      ],
    },
    center: [lng, lat],
    zoom: props.zoom,
  });

  // 修复Canvas定位问题
  map.value.on("load", () => {
    const canvas = mapContainer.value.querySelector(".mapboxgl-canvas");
    if (canvas) canvas.style.position = "relative";
  });
});
</script>

<template>
  <div ref="mapContainer" class="tiandimapbox-container"></div>
</template>

<style scoped>
.tiandimapbox-container {
  width: 100%;
  height: 100vh; /* 明确指定高度 */
  position: relative;
}
</style>
